package cn.sjxy.service;

import cn.sjxy.baseLib.SjuException;
import cn.sjxy.baseLib.SjuSecurity;
import cn.sjxy.mapper.Mp_User;
import cn.sjxy.model.Md_User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class Sv_User {

    @Autowired
    private Mp_User mp_user;

    /**
     * 检查账号是否可以登录
     *
     * @param userCode
     * @param password
     * @return
     */
    public Md_User checkLogin(String userCode, String password) throws Exception {
        QueryWrapper<Md_User> wrapper = new QueryWrapper<>();
        wrapper.eq("userCode", userCode);
        wrapper.eq("password", SjuSecurity.toMD5(password));

        Md_User entry = mp_user.selectOne(wrapper);
        if(entry == null)
            SjuException.appEx("账号或密码错误");

        return entry;
    }

    /**
     * 用户注册
     *
     * @param userCode
     * @param userName
     * @param password
     * @param userSex
     * @throws Exception
     */
    public void register(String userCode, String userName, String password, String userSex) throws Exception {
        // 检查用户账号是否已存在
        QueryWrapper<Md_User> wrapper = new QueryWrapper<>();
        wrapper.eq("userCode", userCode);
        Md_User existUser = mp_user.selectOne(wrapper);
        if (existUser != null) {
            SjuException.appEx("用户账号已存在，请更换");
        }

        // 创建新用户
        Md_User newUser = new Md_User();
        newUser.setUserCode(userCode);
        newUser.setUserName(userName);
        newUser.setPassword(SjuSecurity.toMD5(password)); // MD5加密
        newUser.setUserSex(userSex);
        newUser.setCreateDate(new Date());

        // 插入数据库
        int result = mp_user.insert(newUser);
        if (result <= 0) {
            SjuException.appEx("注册失败，请稍后重试");
        }
    }
}
